﻿using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BitButterECS.DataType;
using BitButterECS.Entity;

namespace BitButterECS.Component
{
    public abstract class BaseComponent
    {
        public BaseComponent()
        {
            Manager.AddComponent(this);
        }

        public virtual bool HasPendingChanges => false;

        public virtual void MergeChanges()
        {
        }

        public void AttachToEntity(BaseEntity entity)
        {
            if (entity.IsManaged && attachedEntityID != entity.ID)
            {
                attachedEntityID = entity.ID;
            }
        }

        public void DetachFromEntity()
        {
            if (AttachedEntity != null)
            {
                attachedEntityID = -1;
            }
        }

        public BaseEntity AttachedEntity => EntityManager.Instance[attachedEntityID];
        int attachedEntityID;

        public int ID
        {
            get => id;
            set
            {
                if (!IsManaged)
                {
                    id = value;
                }
            }
        }
        int id = -1;

        public bool IsManaged => Manager.HasComponent(ID);

        public virtual void Remove()
        {
            Manager.RemoveComponent(this);
        }

        protected ComponentManager Manager => ComponentManager.Instance;
    }
}
